import java.util.ArrayDeque;
import java.util.Deque;

/**
 * @author hewei
 * @version 1.0
 * @description: TODO
 * @date 2022/11/15 16:34
 */

public class ShortestPathBinaryMatrix {

    public static void main(String[] args) {
        int[][] grid = {{0, 1, 1, 0, 1}, {0, 1, 0, 1, 0}, {0, 1, 0, 1, 0}, {1, 0, 1, 1, 0}, {1, 1, 1, 1, 0}};
        System.out.println(new ShortestPathBinaryMatrix().shortestPathBinaryMatrix(grid));
    }

    public int shortestPathBinaryMatrix(int[][] grid) {
        int m = grid.length;
        int n = grid[0].length;
        if (grid[0][0] != 0 || grid[m - 1][n - 1] != 0) return -1;
        if (m == 1 && n == 1) return 1;
        int[][] step = {{-1, -1}, {-1, 1}, {-1, 0}, {1, -1}, {0, 1}, {0, -1}, {1, 0}, {1, 1}};
        Deque<int[]> queue = new ArrayDeque<>();
        queue.offerFirst(new int[]{0, 0});
        int ans = 1;
        grid[0][0] = 2;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ++ans;
            while (size-- > 0) {
                int[] poll = queue.pollLast();
                int i = poll[0];
                int j = poll[1];
                for (int[] ints : step) {
                    int x = i + ints[0];
                    int y = j + ints[1];
                    if (x >= 0 && x < m && y >= 0 && y < n && grid[x][y] == 0) {
                        if (x == m - 1 && y == n - 1) return ans;
                        grid[x][y] = 2;
                        queue.offerFirst(new int[]{x, y});
                    }
                }
            }
        }
        return -1;
    }
}
